package com.dwxt.cdms.service;

import com.dwxt.cdms.entity.Customer;
import com.dwxt.cdms.entity.Relation;
import com.dwxt.common.base.BaseResult;
import com.dwxt.common.base.StatusCode;
import com.dwxt.common.base.YesOrNo;
import org.apache.commons.collections.map.LinkedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ManagerService {

    @Autowired
    private CustomerService customerService;

    @Autowired
    private RelationService relationService;

    public BaseResult selectMyOldRelation(String phone) {
        List<Customer> customerList = customerService.selectByManagerPhone(phone);
        List list = new ArrayList();
        for (Customer customer : customerList) {
            LinkedHashMap myMap = new LinkedHashMap();
            //查询可以看我的关联人 排除自己
            List<Customer> myCustomerList =
                    relationService.selectMyRelationCustomer(customer.getId()).stream()
                            .filter(customer1 -> !phone.equalsIgnoreCase(customer1.getPhone())).collect(Collectors.toList());

            myMap.put("relateId", customer.getId());
            myMap.put("name", customer.getName());
            myMap.put("data", myCustomerList);
            list.add(myMap);
        }
        return BaseResult.ok(list);
    }

    public BaseResult bindWithPhone(Integer relateId, String phone) {
        Customer customer = customerService.selectOrInsert(phone);
        try {
            relationService.insertDefault(relateId, customer.getId());
        } catch (DuplicateKeyException e) {
            return BaseResult.build(StatusCode.ALREADY_RELATION);
        }
        return BaseResult.ok();
    }

    public BaseResult judge(String phone) {
        List<Customer> customerList = customerService.selectByManagerPhone(phone);
        return customerList.size() > 0 ? BaseResult.ok(true) : BaseResult.ok(false);
    }
}
